from flask import Blueprint, render_template, request, redirect, session, url_for
import time

from ..database import db
from ..tools import markdown_to_html


admin = Blueprint("admin", __name__)


@admin.route("/login/", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("admin/login.html")
    else:
        input_password = request.form.get("password")
        correct_password = db.data.find_one({"key": "password_hash"})["value"]
        if input_password == correct_password:
            session["admin_login"] = correct_password
            return redirect(url_for("admin.dashboard"))
        else:
            return render_template("admin/login.html", err="密码错误，请不要重试")


@admin.route("/", methods=["GET"])
def dashboard():
    return render_template("admin/dashboard.html")


@admin.route("/status/", methods=["GET", "POST"])
def status():
    if request.method == "GET":
        return render_template("admin/status.html", status=db.data.find_one({"key": "status"})["value"])
    else:
        status_doc = db.data.find_one({"key": "status"})
        status_doc["value"] = request.form.get("status")
        db.data.update_one({"key": "status"}, {"$set": status_doc})
        return render_template("admin/status.html", msg="修改成功", status=db.data.find_one({"key": "status"})["value"])


@admin.route("/password/", methods=["GET", "POST"])
def password():
    if request.method == "GET":
        return render_template("admin/password.html")
    else:
        input_password_new = request.form.get("password_new")
        input_password_repeat = request.form.get("password_repeat")
        if input_password_new != input_password_repeat:
            return render_template("admin/password.html", err="两次密码不一致")
        else:
            password_doc = db.data.find_one({"key": "password_hash"})
            password_doc["value"] = input_password_new
            db.data.update_one({"key": "password_hash"}, {"$set": password_doc})
            return redirect(url_for("admin.login"))


@admin.route("/article/new/", methods=["GET", "POST"])
def article_new():
    if request.method == "GET":
        return render_template("admin/article_new.html")
    last_article_id_doc = db.data.find_one({"key": "last_article_id"})

    input_category = request.form.get("category")
    input_tag_list = request.form.get("tag").split(",")
    update_article_sign("category", input_category, 1)
    for tag in input_tag_list:
        update_article_sign("tag", tag, 1)

    new_article = {
        "id": last_article_id_doc["value"],
        "title": request.form.get("title"),
        "excerpt": request.form.get("excerpt"),
        "content_md": request.form.get("content"),
        "content_html": markdown_to_html(request.form.get("content")),
        "category": input_category,
        "tag": input_tag_list,
        "date": time.strftime("%Y-%m-%d", time.localtime()),
        "time": time.strftime("%H:%M:%S", time.localtime())
    }
    last_article_id_doc["value"] += 1
    db.data.update_one({"key": "last_article_id"}, {"$set": last_article_id_doc})
    
    db.article.insert_one(new_article)
    return render_template("admin/article_new.html", msg="新建成功")


@admin.route("/article/query/", methods=["GET", "POST"])
def article_query():
    if request.method == "GET":
        return render_template("admin/article_query.html")
    input_id = int(request.form.get("id"))
    if db.article.find_one({"id": input_id}):
        return redirect(url_for("admin.article_edit", article_id=input_id))
    else:
        return render_template("admin/article_query.html", err="文章不存在")


@admin.route("/article/edit/<int:article_id>/", methods=["GET", "POST"])
def article_edit(article_id):
    article_doc = db.article.find_one({"id": article_id})
    if not article_doc:
        return redirect(url_for("admin.article_query"))
    if request.method == "GET":
        return render_template("admin/article_edit.html", article=article_doc)

    old_category = article_doc["category"]
    old_tag_list = article_doc["tag"]
    update_article_sign("category", old_category, -1)
    for tag in old_tag_list:
        update_article_sign("tag", tag, -1)
    
    input_category = request.form.get("category")
    input_tag_list = request.form.get("tag").split(",")
    update_article_sign("category", input_category, 1)
    for tag in input_tag_list:
        update_article_sign("tag", tag, 1)
    
    article_doc["title"] = request.form.get("title")
    article_doc["excerpt"] = request.form.get("excerpt")
    article_doc["content_md"] = request.form.get("content")
    article_doc["content_html"] = markdown_to_html(request.form.get("content"))
    article_doc["category"] = input_category
    article_doc["tag"] = input_tag_list

    db.article.update_one({"id": article_id}, {"$set": article_doc})
    return render_template("admin/article_edit.html", article=article_doc, msg="修改成功")


@admin.route("/article/delete/<int:article_id>/", methods=["GET"])
def article_delete(article_id):
    db.article.remove({"id": article_id})
    return redirect(url_for("admin.article_query"))


@admin.route("/page/new/", methods=["GET", "POST"])
def page_new():
    if request.method == "GET":
        return render_template("admin/page_new.html")
    new_page = {
        "name": request.form.get("name"),
        "icon": request.form.get("icon"),
        "title": request.form.get("title"),
        "content_md": request.form.get("content"),
        "content_html": markdown_to_html(request.form.get("content"))
    }
    db.page.insert_one(new_page)
    return render_template("admin/page_new.html", msg="新建成功")


@admin.route("/page/query/", methods=["GET", "POST"])
def page_query():
    if request.method == "GET":
        return render_template("admin/page_query.html")
    input_name = request.form.get("name")
    if db.page.find_one({"name": input_name}):
        return redirect(url_for("admin.page_edit", page_name=input_name))
    else:
        return render_template("admin/page_query.html", err="页面不存在")


@admin.route("/page/edit/<page_name>/", methods=["GET", "POST"])
def page_edit(page_name):
    page_doc = db.page.find_one({"name": page_name})
    if not page_doc:
        return redirect(url_for("admin.page_query"))
    if request.method == "GET":
        return render_template("admin/page_edit.html", page=page_doc)
    
    page_doc["title"] = request.form.get("title")
    page_doc["name"] = request.form.get("name")
    page_doc["icon"] = request.form.get("icon")
    page_doc["content_md"] = request.form.get("content")
    page_doc["content_html"] = markdown_to_html(request.form.get("content"))
    db.page.update_one({"name": page_name}, {"$set": page_doc})
    return render_template("admin/page_edit.html", page=page_doc, msg="修改成功")


@admin.route("/page/delete/<page_name>/", methods=["GET"])
def page_delete(page_name):
    db.page.remove({"name": page_name})
    return redirect(url_for("admin.page_query"))


@admin.before_request
def not_login():
    if request.path == url_for("admin.login"):
        return None
    correct_password = db.data.find_one({"key": "password_hash"})["value"]
    if not (session.get("admin_login", default = False) == correct_password):
        return redirect(url_for("admin.login"))


def update_article_sign(kind, name, inc):
    tag_doc = db[kind].find_one({"name": name})
    if tag_doc:
        if tag_doc["count"] == 1 and inc == -1:
            db[kind].delete_one({"name": name})
        else:
            tag_doc["count"] += inc
            db[kind].update_one({"name": name}, {"$set": tag_doc})
    else:
        db[kind].insert_one({
            "name": name,
            "count": 1
        })

